import axios from 'axios'
import store from '@/store'
import router from '@/router/index'
// 设置基地址
const baseUrl = 'https://apipc-xiaotuxian-front.itheima.net/'
const request = axios.create({
  baseURL: baseUrl
})
// 请求拦截器
request.interceptors.request.use(
  config => {
    // 统一添加请求头
    const token = store.state.user.profile.token
    if (token) {
      // 已经登录成功，统一添加token
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// 响应拦截器
request.interceptors.response.use(
  res => {
    return res.data
  },
  err => {
    if (err.response && err.response.status === 401) {
      return router.push('/login')
    }
    return Promise.reject(err)
  }
)

// 导出函数
export default data => {
  return request({
    method: data.method || 'GET',
    url: data.url,
    [data.method.toUpperCase() === 'GET' ? 'params' : 'data']: data.data
  })
}
